<template>
  <div class="select-goods">
    <div class="goods-header">
      <h3>选择商品</h3>
      <p class="goods-tip">您可以选择购买以下商品，也可以直接报名参赛</p>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-state">
      <p>正在加载商品...</p>
    </div>

    <!-- 商品列表 -->
    <div class="goods-list" v-else>
      <div
        v-for="product in products"
        :key="product.id"
        class="product-card"
        :class="{ 'selected': isProductSelected(product.id) }"
        @click="toggleProduct(product)"
      >
        <div class="product-image">
          <img :src="product.pic || '/images/default-product.jpg'" :alt="product.name" />
          <div class="product-badge" v-if="isProductSelected(product.id)">
            <svg viewBox="0 0 24 24" width="16" height="16">
              <path fill="currentColor" d="M9,20.42L2.79,14.21L5.62,11.38L9,14.77L18.88,4.88L21.71,7.71L9,20.42Z" />
            </svg>
          </div>
        </div>
        <div class="product-info">
          <h4 class="product-name">{{ product.name }}</h4>
          <p class="product-desc" v-html="product.detailMobileHtml || product.detailHtml"></p>
          <div class="product-price">¥{{ product.price }}</div>
          <div class="product-brand" v-if="product.brandName">{{ product.brandName }}</div>
          <div class="product-category" v-if="product.productCategoryName">{{ product.productCategoryName }}</div>
          <div class="product-sku-info">
            <span v-if="product.skus && product.skus.length > 0" class="has-sku">多规格</span>
            <span v-else class="no-sku">单规格</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="!loading && products.length === 0" class="empty-state">
      <p>暂无可购买的商品</p>
    </div>

    <!-- SKU选择弹窗 -->
    <div class="sku-modal" v-if="showSkuModal" @click="closeSkuModal">
      <div class="sku-content" @click.stop>
        <div class="sku-header">
          <h4>{{ currentProduct.name }}</h4>
          <button class="close-btn" @click="closeSkuModal">
            <svg viewBox="0 0 24 24" width="20" height="20">
              <path fill="currentColor" d="M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z" />
            </svg>
          </button>
        </div>

        <div class="sku-body">
          <div class="product-preview">
            <img :src="currentProduct.pic || '/images/default-product.jpg'" :alt="currentProduct.name" />
            <div class="product-details">
              <h5>{{ currentProduct.name }}</h5>
              <p class="price">¥{{ getCurrentSkuPrice() }}</p>
            </div>
          </div>

          <!-- 显示可用SKU列表 -->
          <div class="available-skus" v-if="currentProduct.skus && currentProduct.skus.length > 0">
            <label class="sku-label">选择规格</label>
            <div class="sku-list">
              <div
                v-for="sku in currentProduct.skus"
                :key="sku.id"
                class="sku-option"
                :class="{ 'selected': selectedSkuId === sku.id, 'out-of-stock': sku.stock <= 0 }"
                @click="selectSkuById(sku.id)"
              >
                <div class="sku-info">
                  <span class="sku-spec">{{ formatSkuSpec(sku.spData) }}</span>
                  <span class="sku-price">¥{{ sku.price }}</span>
                </div>
                <div class="sku-stock">库存: {{ sku.stock }}</div>
              </div>
            </div>
          </div>

          <!-- 没有SKU的商品 -->
          <div v-else class="no-sku-info">
            <div class="single-spec">
              <span class="spec-label">规格：</span>
              <span class="spec-value">默认规格</span>
            </div>
            <div class="single-price">
              <span class="price-label">价格：</span>
              <span class="price-value">¥{{ currentProduct.price }}</span>
            </div>
          </div>

          <div class="quantity-selector">
            <label class="quantity-label">数量</label>
            <div class="quantity-controls">
              <button
                class="quantity-btn"
                @click="decreaseQuantity(currentProduct.id)"
                :disabled="getProductQuantity(currentProduct.id) <= 1"
              >
                -
              </button>
              <span class="quantity-value">{{ getProductQuantity(currentProduct.id) }}</span>
              <button
                class="quantity-btn"
                @click="increaseQuantity(currentProduct.id)"
                :disabled="getCurrentSkuStock() <= getProductQuantity(currentProduct.id)"
              >
                +
              </button>
            </div>
            <div class="stock-info" v-if="getCurrentSkuStock() > 0">
              剩余库存: {{ getCurrentSkuStock() }}
            </div>
          </div>
        </div>

        <div class="sku-footer">
          <button class="confirm-btn" @click="confirmSku" :disabled="!canConfirmSku()">确认选择</button>
        </div>
      </div>
    </div>

    <!-- 已选商品汇总 -->
    <div class="selected-summary" v-if="selectedProductsData.length > 0">
      <h4>已选商品</h4>
      <div class="summary-list">
        <div
          v-for="item in selectedProductsData"
          :key="`${item.productId}-${item.skuId || 'default'}`"
          class="summary-item"
        >
          <div class="summary-info">
            <span class="summary-name">{{ item.productName }}</span>
            <span class="summary-sku">{{ item.skuSpec }}</span>
            <span class="summary-quantity">x{{ item.quantity }}</span>
          </div>
          <div class="summary-price">¥{{ (item.price * item.quantity).toFixed(2) }}</div>
          <button class="remove-btn" @click="removeProduct(item.productId, item.skuId)">
            <svg viewBox="0 0 24 24" width="16" height="16">
              <path fill="currentColor" d="M19,6.41L17.59,5L12,10.59L6.41,5L5,6.41L10.59,12L5,17.59L6.41,19L12,13.41L17.59,19L19,17.59L13.41,12L19,6.41Z" />
            </svg>
          </button>
        </div>
      </div>
      <div class="summary-total">
        <span class="total-label">总计：</span>
        <span class="total-price">¥{{ totalPrice.toFixed(2) }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, defineEmits, onMounted } from 'vue'
import { getEvtGoods } from '@/api/data.js'
import { useEventStore } from '@/stores/event/index.js'

const eventStore = useEventStore()
const emit = defineEmits(['update:selectedGoods'])

// 商品数据
const products = ref([])
const loading = ref(false)

// 状态管理
const selectedProductsData = ref([])
const showSkuModal = ref(false)
const currentProduct = ref({})
const selectedSkuId = ref(null)
const currentQuantity = ref(1)

// 获取商品数据
const getAllEvtGoods = async () => {
  try {
    loading.value = true
    const res = await getEvtGoods({ evtId: eventStore.eventData.id })
    if (res && res.data) {
      // 过滤已发布的商品
      products.value = res.data
    }
  } catch (error) {
    console.error('获取商品数据失败:', error)
    products.value = []
  } finally {
    loading.value = false
  }
}

// 检查商品是否已选择
const isProductSelected = (productId) => {
  return selectedProductsData.value.some(item => item.productId === productId)
}

// 切换商品选择
const toggleProduct = (product) => {
  // 检查是否已经选择了该商品
  const existingIndex = selectedProductsData.value.findIndex(item => item.productId === product.id)

  if (existingIndex > -1) {
    // 如果已选择，则移除
    selectedProductsData.value.splice(existingIndex, 1)
    updateSelectedGoods()
    return
  }

  // 如果未选择，则打开选择弹窗
  currentProduct.value = product
  selectedSkuId.value = null
  currentQuantity.value = 1

  // 如果商品没有SKU，直接添加到购物车
  if (!product.skus || product.skus.length === 0) {
    addToCart(product, null, 1)
    return
  }

  // 如果有SKU，打开选择弹窗
  showSkuModal.value = true
}

// 添加到购物车
const addToCart = (product, sku, quantity) => {
  const cartItem = {
    productId: product.id,
    skuId: sku ? sku.id : null,
    productName: product.name,
    price: sku ? sku.price : product.price,
    skuSpec: sku ? formatSkuSpec(sku.spData) : '默认规格',
    quantity: quantity,
    outSkuId: sku ? sku.outSkuId : null,
    outProductId: product.outProductId,
    brandName: product.brandName,
    categoryName: product.productCategoryName,
    pic: product.pic
  }

  selectedProductsData.value.push(cartItem)
  updateSelectedGoods()
}

// 通过SKU ID选择
const selectSkuById = (skuId) => {
  const sku = currentProduct.value.skus.find(s => s.id === skuId)
  if (sku && sku.stock > 0) {
    selectedSkuId.value = skuId
  }
}

// 格式化SKU规格
const formatSkuSpec = (spData) => {
  if (!spData) return '默认规格'
  try {
    const spec = JSON.parse(spData)
    return Object.entries(spec)
      .filter(([key, value]) => value !== null && value !== '' && value !== undefined)
      .map(([key, value]) => `${key}: ${value}`)
      .join(', ') || '默认规格'
  } catch (error) {
    return '默认规格'
  }
}

// 获取当前选中的SKU
const getCurrentSku = () => {
  if (!selectedSkuId.value || !currentProduct.value.skus) return null
  return currentProduct.value.skus.find(sku => sku.id === selectedSkuId.value)
}

// 获取当前SKU价格
const getCurrentSkuPrice = () => {
  const sku = getCurrentSku()
  return sku ? sku.price : currentProduct.value.price
}

// 获取当前SKU库存
const getCurrentSkuStock = () => {
  const sku = getCurrentSku()
  return sku ? sku.stock : 999
}

// 检查是否可以确认SKU
const canConfirmSku = () => {
  // 如果没有SKU，可以直接确认
  if (!currentProduct.value.skus || currentProduct.value.skus.length === 0) {
    return true
  }
  // 如果有SKU，必须选择一个且有库存
  return selectedSkuId.value !== null && getCurrentSkuStock() > 0
}

// 数量控制
const getProductQuantity = (productId) => {
  return currentQuantity.value
}

const increaseQuantity = (productId) => {
  const maxStock = getCurrentSkuStock()
  if (currentQuantity.value < maxStock) {
    currentQuantity.value++
  }
}

const decreaseQuantity = (productId) => {
  if (currentQuantity.value > 1) {
    currentQuantity.value--
  }
}

// 关闭SKU弹窗
const closeSkuModal = () => {
  showSkuModal.value = false
  selectedSkuId.value = null
  currentQuantity.value = 1
}

// 确认SKU选择
const confirmSku = () => {
  if (!canConfirmSku()) return

  const sku = getCurrentSku()
  addToCart(currentProduct.value, sku, currentQuantity.value)

  showSkuModal.value = false
  selectedSkuId.value = null
  currentQuantity.value = 1
}

// 移除商品
const removeProduct = (productId, skuId = null) => {
  const index = selectedProductsData.value.findIndex(item =>
    item.productId === productId && item.skuId === skuId
  )
  if (index > -1) {
    selectedProductsData.value.splice(index, 1)
    updateSelectedGoods()
  }
}

// 总价计算
const totalPrice = computed(() => {
  return selectedProductsData.value.reduce((total, item) => {
    return total + (item.price * item.quantity)
  }, 0)
})

// 更新选中商品数据到父组件
const updateSelectedGoods = () => {
  emit('update:selectedGoods', {
    products: selectedProductsData.value,
    totalPrice: totalPrice.value
  })
}

onMounted(() => {
  getAllEvtGoods()
})
</script>

<style scoped lang="scss">
.select-goods {
  padding: 20px 0;
}

.goods-header {
  margin-bottom: 30px;
  text-align: center;

  h3 {
    font-size: 24px;
    font-weight: 600;
    color: #333;
    margin: 0 0 10px 0;
  }

  .goods-tip {
    color: #666;
    font-size: 14px;
    margin: 0;
  }
}

.loading-state {
  text-align: center;
  padding: 40px 0;
  color: #666;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
  color: #999;
}

.goods-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.product-card {
  border: 2px solid #e9ecef;
  border-radius: 12px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #fff;
  position: relative;

  &:hover {
    border-color: #6b46c1;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(107, 70, 193, 0.15);
  }

  &.selected {
    border-color: #6b46c1;
    background: #f3f0ff;
  }
}

.product-image {
  position: relative;
  width: 100%;
  height: 160px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .product-badge {
    position: absolute;
    top: 10px;
    right: 10px;
    width: 24px;
    height: 24px;
    background: #6b46c1;
    color: #fff;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.product-info {
  .product-name {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin: 0 0 8px 0;
  }

  .product-desc {
    font-size: 14px;
    color: #666;
    margin: 0 0 12px 0;
    line-height: 1.4;
    max-height: 40px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }

  .product-price {
    font-size: 18px;
    font-weight: 600;
    color: #6b46c1;
    margin-bottom: 5px;
  }

  .product-brand {
    font-size: 12px;
    color: #999;
    margin-bottom: 2px;
  }

  .product-category {
    font-size: 12px;
    color: #999;
    margin-bottom: 5px;
  }

  .product-sku-info {
    font-size: 12px;

    .has-sku {
      color: #6b46c1;
      background: #f3f0ff;
      padding: 2px 6px;
      border-radius: 4px;
    }

    .no-sku {
      color: #28a745;
      background: #f0f9f0;
      padding: 2px 6px;
      border-radius: 4px;
    }
  }
}

// SKU弹窗样式
.sku-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.sku-content {
  background: #fff;
  border-radius: 12px;
  width: 90%;
  max-width: 500px;
  max-height: 80vh;
  overflow-y: auto;
}

.sku-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 20px 0 20px;

  h4 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: #333;
  }

  .close-btn {
    background: none;
    border: none;
    cursor: pointer;
    color: #666;

    &:hover {
      color: #333;
    }
  }
}

.sku-body {
  padding: 20px;
}

.product-preview {
  display: flex;
  gap: 15px;
  margin-bottom: 25px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e9ecef;

  img {
    width: 80px;
    height: 80px;
    object-fit: cover;
    border-radius: 8px;
    background: #f8f9fa;
  }

  .product-details {
    flex: 1;

    h5 {
      margin: 0 0 8px 0;
      font-size: 16px;
      font-weight: 600;
      color: #333;
    }

    .price {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
      color: #6b46c1;
    }
  }
}

.available-skus {
  margin-bottom: 20px;

  .sku-label {
    display: block;
    font-size: 14px;
    font-weight: 500;
    color: #333;
    margin-bottom: 10px;
  }

  .sku-list {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

  .sku-option {
    padding: 12px;
    border: 1px solid #e9ecef;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover:not(.out-of-stock) {
      border-color: #6b46c1;
    }

    &.selected {
      border-color: #6b46c1;
      background: #f3f0ff;
    }

    &.out-of-stock {
      opacity: 0.5;
      cursor: not-allowed;
      background: #f8f9fa;
    }

    .sku-info {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 4px;

      .sku-spec {
        font-size: 14px;
        color: #333;
      }

      .sku-price {
        font-size: 14px;
        font-weight: 600;
        color: #6b46c1;
      }
    }

    .sku-stock {
      font-size: 12px;
      color: #666;
    }
  }
}

.no-sku-info {
  background: #f8f9fa;
  border-radius: 6px;
  padding: 20px;
  margin-bottom: 20px;

  .single-spec {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;

    .spec-label {
      font-size: 14px;
      color: #666;
    }

    .spec-value {
      font-size: 14px;
      color: #333;
      font-weight: 500;
    }
  }

  .single-price {
    display: flex;
    justify-content: space-between;

    .price-label {
      font-size: 14px;
      color: #666;
    }

    .price-value {
      font-size: 16px;
      color: #6b46c1;
      font-weight: 600;
    }
  }
}

.quantity-selector {
  display: flex;
  align-items: center;
  gap: 15px;

  .quantity-label {
    font-size: 14px;
    font-weight: 500;
    color: #333;
  }

  .quantity-controls {
    display: flex;
    align-items: center;
    gap: 10px;

    .quantity-btn {
      width: 32px;
      height: 32px;
      border: 1px solid #e9ecef;
      background: #fff;
      border-radius: 4px;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 16px;
      font-weight: 500;

      &:hover:not(:disabled) {
        border-color: #6b46c1;
        color: #6b46c1;
      }

      &:disabled {
        opacity: 0.5;
        cursor: not-allowed;
      }
    }

    .quantity-value {
      min-width: 30px;
      text-align: center;
      font-size: 16px;
      font-weight: 500;
    }
  }

  .stock-info {
    font-size: 12px;
    color: #666;
  }
}

.sku-footer {
  padding: 0 20px 20px 20px;

  .confirm-btn {
    width: 100%;
    padding: 12px;
    background: #6b46c1;
    color: #fff;
    border: none;
    border-radius: 6px;
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;

    &:hover:not(:disabled) {
      background: #553c9a;
    }

    &:disabled {
      background: #ccc;
      cursor: not-allowed;
    }
  }
}

// 已选商品汇总
.selected-summary {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
  margin-top: 30px;

  h4 {
    margin: 0 0 15px 0;
    font-size: 16px;
    font-weight: 600;
    color: #333;
  }
}

.summary-list {
  margin-bottom: 15px;
}

.summary-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 0;
  border-bottom: 1px solid #e9ecef;

  &:last-child {
    border-bottom: none;
  }

  .summary-info {
    flex: 1;

    .summary-name {
      font-weight: 500;
      color: #333;
      margin-right: 10px;
    }

    .summary-sku {
      font-size: 12px;
      color: #666;
      margin-right: 10px;
    }

    .summary-quantity {
      font-size: 12px;
      color: #666;
    }
  }

  .summary-price {
    font-weight: 600;
    color: #6b46c1;
    margin-right: 10px;
  }

  .remove-btn {
    background: none;
    border: none;
    cursor: pointer;
    color: #999;
    padding: 4px;

    &:hover {
      color: #f44336;
    }
  }
}

.summary-total {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 15px;
  border-top: 1px solid #e9ecef;

  .total-label {
    font-size: 16px;
    font-weight: 500;
    color: #333;
  }

  .total-price {
    font-size: 18px;
    font-weight: 600;
    color: #6b46c1;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .goods-list {
    grid-template-columns: 1fr;
  }

  .sku-content {
    width: 95%;
    margin: 20px;
  }

  .summary-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .quantity-selector {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>
